<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>组件通信</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>

<body>

    <div id="app">
        <blabber :ice-breaker="true"></blabber>
        <blabber></blabber>
    </div>

    <script>
        var line = 0;
        var bus = new Vue();
        Vue.component('blabber', {
            template: "<p>{{dialogue[currentLine]}}</p>",
            props: {
                iceBreaker:{
                    type: Boolean,
                    default: false
                }
            },
            data() {
                return {
                    currentLine: this.iceBreaker ? 0 : -1,
                    dialogue: [
                        'hello',
                        'how are you?',
                        'fine thanks',
                        'lets go drink!',
                        'alright, where?',
                        'to hellos bar',
                        'hello?'
                    ]
                }
            },
            // 当第二个组件执行时，先执行这里
            created(){
                bus.$on('line', line=>{
                    if(line !== this.currentLine){
                        setTimeout(() => {
                            this.currentLine = (line + 1) % this.dialogue.length;
                            // 发送给第一个组件接受
                            bus.$emit('line', this.currentLine);
                        }, 2000);
                    }
                })
            },
            // 在第一个组件执行，触发发送器，将信息发送给第二个组件
            mounted() {
                if(this.iceBreaker){
                    bus.$emit('line', 0);
                }
            }
        })
        new Vue({
            el: '#app'
        })
    </script>

</body>

</html>